﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShiNiu.ServiceStackRedis
{
     
    public class RedisManager 
    {

        // <summary>
        /// redis配置文件信息
        /// </summary>
        private static RedisConfig Config = RedisConfig.GetConfig();
        //public static IRedisClient Core { get; private set; }
        //public   RedisClient Redis = new RedisClient(); 
        private static readonly object obj = new object();
        //缓存池
        public static PooledRedisClientManager prcm = new PooledRedisClientManager();
        private static readonly Lazy<IRedisClient> RedisLazy = new Lazy<IRedisClient>(() =>
        {
            IRedisClient redisClient = prcm.GetClient();
            redisClient.Password = Config.PassWord;
            return redisClient;
        });

        static RedisManager()
        {
            CreateManager();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisManager()
        {
        }

        /// <summary>
        /// 缓冲池
        /// </summary>
        /// <param name="readWriteHosts"></param>
        /// <param name="readOnlyHosts"></param>
        /// <returns></returns>
        public static PooledRedisClientManager CreateManager()
        {
            //if (prcm == null)
            //{ 
            //    lock (obj)
            //    {
            //        if (prcm == null)
            //        {
            string[] WriteServerConStr = SplitString(Config.WriteServerConStr, ",");
            string[] ReadServerConStr = SplitString(Config.ReadServerConStr, ",");
            RedisClientManagerConfig RedisClientConfig = new RedisClientManagerConfig
            {
                MaxWritePoolSize = Config.MaxWritePoolSize,
                MaxReadPoolSize = Config.MaxReadPoolSize,
                AutoStart = Config.AutoStart,
            };
            prcm = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr, RedisClientConfig) { ConnectTimeout = 1000 * 60 * 20 };
            //        }
            //    } 
            //}
            return prcm;
        }

        //弃用
        [Obsolete("ClientRedis弃用 使用RedisClient()")]
        public static IRedisClient GetClientRedis
        {
            get
            {
                return RedisLazy.Value;
            }
        }

        public static IRedisClient GetClient()
        {
            IRedisClient redisClient = prcm.GetClient();
            redisClient.Password = Config.PassWord;
            return redisClient;
        }

        private static string[] SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        } 

    }

}
